import cgi
import os
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app

class FlogPost(db.Model):
  usuario = db.UserProperty()
  descripcion = db.StringProperty(multiline=True)
  foto = db.BlobProperty()
  fecha = db.DateTimeProperty(auto_now_add=True)

class Principal(webapp.RequestHandler):
  def get(self): 
    path=os.path.join(os.path.dirname(__file__), 'index.htm')
    user = users.get_current_user()
    if user:
      valores_template = {
       'login_texto': 'cerrar sesion %s' % user.nickname(),
       'login_url': users.create_logout_url(self.request.uri),
       'estaLogueado': True,
       'flog_url': '/' + user.nickname(),
       }
    else:
      valores_template = {
       'login_texto': 'iniciar sesion',
       'login_url': users.create_login_url(self.request.uri),
       }
    
    self.response.out.write(template.render(path, valores_template))
    
class Upload(webapp.RequestHandler):
    def get(self):
      path=os.path.join(os.path.dirname(__file__), 'upload.htm')
      self.response.out.write(template.render(path, None))
    
      
    def post(self):
      newPost=FlogPost()
      newPost.usuario=users.get_current_user()
      newPost.descripcion=self.request.get('descripcion')
      newPost.foto=db.Blob(self.request.get('img'))
      newPost.put()
      self.redirect('/')
      
class UserFlog(webapp.RequestHandler):
  def get(self):
    posts=FlogPost.all()
    posts=posts.fetch(1)
    for post in posts:
      self.response.out.write('<br/>')
      self.response.out.write(post.fecha)
      self.response.out.write('<br/>')
      self.response.out.write(post.usuario)
      self.response.out.write('<br/>')
      self.response.out.write(post.descripcion)
      self.response.out.write('<br/>')
      self.response.out.write('<br/>')
      self.response.out.write('-----')
      self.response.out.write('<br/>')

class Foto(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type']='image/jpeg'
    posts=FlogPost.all()
    posts=posts.fetch(1)
    self.response.out.write(posts[0].foto)
  	
      
    
    

        


application = webapp.WSGIApplication(
                                     [('/', Principal),('/upload',Upload),('/foto/.*',Foto),('/.*',UserFlog)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()